#include "wx/wxprec.h"
#if wxUSE_COLOURPICKERCTRL

#include "wx/clrpicker.h"

#ifndef WX_PRECOMP
#include "wx/textctrl.h"
#endif

const wxChar wxColourPickerCtrlNameStr[] = wxT( "colourpicker" );
const wxChar wxColourPickerWidgetNameStr[] = wxT( "colourpickerwidget" );

DEFINE_EVENT_TYPE( wxEVT_COMMAND_COLOURPICKER_CHANGED )
IMPLEMENT_DYNAMIC_CLASS( wxColourPickerCtrl, wxPickerBase )
IMPLEMENT_DYNAMIC_CLASS( wxColourPickerEvent, wxEvent )

#define M_PICKER     ((wxColourPickerWidget*)m_picker)

bool wxColourPickerCtrl::Create( wxWindow *parent, wxWindowID id, const wxColour &col,
                                 const wxPoint &pos, const wxSize &size,
                                 long style, const wxValidator& validator,
                                 const wxString &name ) {
  if( !wxPickerBase::CreateBase( parent, id, col.GetAsString(), pos, size,
                                 style, validator, name ) ) {
    return false;
  }
  m_picker = new wxColourPickerWidget( this, wxID_ANY, col, wxDefaultPosition, wxDefaultSize,
                                       GetPickerStyle( style ) );
  wxPickerBase::PostCreation();
  m_picker->Connect( wxEVT_COMMAND_COLOURPICKER_CHANGED,
                     wxColourPickerEventHandler( wxColourPickerCtrl::OnColourChange ),
                     NULL, this );
  return true;
}

void wxColourPickerCtrl::SetColour( const wxColour &col ) {
  M_PICKER->SetColour( col );
  UpdateTextCtrlFromPicker();
}

bool wxColourPickerCtrl::SetColour( const wxString &text ) {
  wxColour col( text );
  if( !col.Ok() ) {
    return false;
  }
  M_PICKER->SetColour( col );
  UpdateTextCtrlFromPicker();
  return true;
}

void wxColourPickerCtrl::UpdatePickerFromTextCtrl() {
  wxASSERT( m_text );
  if( m_bIgnoreNextTextCtrlUpdate ) {
    m_bIgnoreNextTextCtrlUpdate = false;
    return;
  }
  wxColour col( m_text->GetValue() );
  if( !col.Ok() ) {
    return;
  }
  if( M_PICKER->GetColour() != col ) {
    M_PICKER->SetColour( col );
    wxColourPickerEvent event( this, GetId(), col );
    GetEventHandler()->ProcessEvent( event );
  }
}

void wxColourPickerCtrl::UpdateTextCtrlFromPicker() {
  if( !m_text ) {
    return;
  }
  m_bIgnoreNextTextCtrlUpdate = true;
  m_text->SetValue( M_PICKER->GetColour().GetAsString() );
}

void wxColourPickerCtrl::OnColourChange( wxColourPickerEvent &ev ) {
  UpdateTextCtrlFromPicker();
  wxColourPickerEvent event( this, GetId(), ev.GetColour() );
  GetEventHandler()->ProcessEvent( event );
}

#endif
